package com.billdowney.controller.main;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.billdowney.annotation.AuthRoleAllowed;
import com.billdowney.controller.BaseController;
import com.billdowney.service.interfaces.system.SystemDataDictService;
import com.billdowney.service.util.system.SystemDataDictConst;
import com.billdowney.util.CommonUtil;
import com.billdowney.util.auth.AuthRoleConst;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

@Controller
@RequestMapping(method = { RequestMethod.POST, RequestMethod.GET })
@Api(tags = "错误页面处理控制器")
public class ErrorController extends BaseController {

	@Autowired
	private SystemDataDictService systemDataDictService;

	@AuthRoleAllowed(AuthRoleConst.NOT_LOGIN)
	@RequestMapping(value = "/error/{code}")
	@ApiOperation(value = "错误代码页面处理")
	@ApiImplicitParam(name = "code", value = "错误代码", required = true)
	public String errorCodePage(@PathVariable int code, Model model) throws Exception {
		model.addAttribute("httpStatus", HttpStatus.valueOf(code));
		model.addAttribute("indexPath", request.getScheme() + "://" + request.getServerName() + ":"
				+ request.getServerPort() + request.getContextPath());
		String errorPageFolderPath = systemDataDictService.getString(SystemDataDictConst.errorPageFolderPath);
		if (CommonUtil.isEmpty(errorPageFolderPath)) {
			return "errorPage/" + code;
		}
		return errorPageFolderPath + "/" + code;
	}

	@Bean
	public WebServerFactoryCustomizer<ConfigurableWebServerFactory> initWebServerFactoryCustomizer() {
		return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
			@Override
			public void customize(ConfigurableWebServerFactory factory) {
				// 配置需要转发的code
				Integer[] configCodeArr = { 4, 5 };
				List<Integer> configCodeList = Arrays.asList(configCodeArr);
				List<ErrorPage> errorPageList = new ArrayList<>();
				for (HttpStatus status : HttpStatus.values()) {
					if (configCodeList.contains(status.series().value())) {
						errorPageList.add(new ErrorPage(status, "/error/" + status.value()));
					}
				}
				factory.addErrorPages(errorPageList.toArray(new ErrorPage[errorPageList.size()]));
			}
		};
	}

}
